new Vue({

    el:"#app",
    data:{
        pagination:{

            queryString:"",
            currentPage:1,
            pageSize:5,
            pageSizes:[1,5,10,20],
            total:0,
        },

        // 表格中要显示的体检中心的信息
        dataList:[],

        addFormVisible:false,

        updateFormVisible:false,

        formData:{},

        //校验规则
        rules:{

            name:[{required:true , message:"名称属性必须要填写" , trigger:"blur"},
                { min: 5, max: 30, message: "长度在 5 到 30 个字符", trigger: "blur" }
            ],
            phone:[
                {required: true , message: "电话属性必须要填写" , trigger: "blur"},
                {pattern:/(^1[3456789][0-9]{9}$)/, message: '你的电话号码格式不正确' }
            ]
        },

        imageUrl:null,

        autoUpload:true,

        lastQueryString:"",

        mapVisible:false,

        flag:false,

        //地图搜索时使用的属性
        searchAddress:"",

        updateFormVisible: false,

        // 在更新时使用 ， 判断更新之前有没有图片
        hasOldImg:"",


        lastLocation:"",
        lastAddress:"",


        authority:{
            ADDRESS_ADD:"",
            ADDRESS_EDIT:"",
            ADDRESS_QUERY:"",
            ADDRESS_DELETE:""
        }



    },

    methods: {

        findWithPage() {
            if(this.pagination.queryString.length != 0){

                if(this.lastQueryString != this.pagination.queryString){

                    this.pagination.currentPage = 1;
                }
            }

            this.lastQueryString = this.pagination.queryString ;

            let _this = this;

            let param = {

                currentPage: this.pagination.currentPage,
                pageSize: this.pagination.pageSize,
                queryString: this.pagination.queryString

            };

            axios.post("/address/findWithPage.do" , param)
                .then(function(resp){

                    _this.pagination.total = resp.data.total;
                    _this.dataList = resp.data.rows;

                })
                .catch(function(error){
                    alert(error);
                })



        },

        openAddForm() {

            this.addFormVisible = true;

        },

        resetForm(){
            this.formData = {};
            this.mapVisible = false;
            this.imageUrl = "";
            this.pagination.queryString = "";
            this.lastQueryString = "";
            this.hasOldImg = "";

            this.lastAddress = "";
            this.lastLocation = "";

        },

        closeAddForm() {

            this.resetForm();
            this.addFormVisible = false;


        },

        addAddress() {

            let _this = this;

            //首先进行信息验证
            this.$refs['addForm'].validate(function(res){

                if(res){
                    //校验通过
                    axios.post("/address/addAddress.do" , _this.formData)

                        .then(function(resp){

                            if(resp.data.flag){

                                //添加数据之后的总数
                                let total = _this.pagination.total + 1;
                                let size = _this.pagination.pageSize;

                                //添加之后始终都跳转到最后一页
                                if(total % size == 0){

                                    _this.pagination.currentPage = total / size;

                                }else{

                                    _this.pagination.currentPage = Math.ceil(total / size);

                                }



                                _this.$message.success(resp.data.message);

                                _this.findWithPage();

                                _this.closeAddForm();


                            }else{

                                _this.$message.warning(resp.data.message);

                                _this.closeAddForm();

                            }

                        })

                }else{

                    _this.$message.warning("您输入的信息不符合校验规则，请检查后重新输入");

                }
            })

        },

        //判断地址
       chargeAddress(address){
            let array = address.split(",");

           if (array.length < 4) {
               return false;
           }else{

               return true;
           }

       },


        beforeUpload(file) {
            //对要上传的文件做一些判断的工作
            const isJpg = file.type === 'image/jpeg';

            //上传文件的大小不能够超过 30 M
            const sizeCondition = (file.size/1024/1024 <= 30);

            if(!isJpg){
                this.$message.error("上传的文件必须是后缀为jpg格式的图片")
            }

            if(!sizeCondition){
                this.$message.error(" 文件过大 ，上传的文件必须要小于 30 M")
            }

            // 返回值为 true 再会进行文件上传的具体工作
            return isJpg && sizeCondition;

        },

        uploadSuccess(response, file) {

            if(response.flag){

                this.imageUrl = "http://qgivvdn22.hd-bkt.clouddn.com/" + response.data;

                this.formData.image = response.data;

                this.$message.success(response.message);

            }else{

                this.$message.error(response.message);
            }

        },


        //开启地图
        openMap() {

            let _this = this;
            this.mapVisible = true;

            let map = new BMap.Map("mapContainer");


            //设置初始地址 ， 以及显示的尺寸
            map.centerAndZoom("合肥", 18);
            let geoc = new BMap.Geocoder();

            //开启鼠标滚轮缩放
            map.enableScrollWheelZoom(true);

            // 平移缩放控件
            // map.addControl(new BMap.NavigationControl());
            //添加城市列表插件
            let size = new BMap.Size(20, 60);   // size 是在设置地图控件所在的位置
            map.addControl(new BMap.CityListControl({
                anchor: BMAP_ANCHOR_TOP_LEFT,
                offset: size,
                // 切换城市之前事件
                /*onChangeBefore: function(){

                   alert('before');
                },
               // 切换城市之后事件
               onChangeAfter:function(){
                  alert('after');
                }*/
            }));


            //为搜索框绑定事件

            //添加地图点击事件
            map.addEventListener("click", function (e) {


                let pt = e.point;
                //将点击的地图经纬度回显到输入框中
                _this.formData.location = pt.lng + "," + pt.lat;

                //对点击的地址进行解析(逆解析)
                geoc.getLocation(pt, function (rs) {

                    let addComp = rs.addressComponents;
                    let address = "";
                    addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber;
                   if(addComp.province){
                       address += addComp.province;
                   }

                   if(addComp.city){
                       address +="," +  addComp.city;
                   }

                   if( addComp.district){
                       address += " , " + addComp.district;
                   }

                   if(addComp.street){
                       address += " , " + addComp.street;
                   }

                   if(addComp.streetNumber){
                       address +=" , " + addComp.streetNumber;
                   }

                    _this.formData.address = address;

                   if(_this.chargeAddress(address)){
                       _this.$message.success(address);
                   }else{
                       _this.$message.warning(address + "  当前地址不可用");
                   }



                    //在地图上添加标记物 （首先需要清空所有的标记物）
                    map.clearOverlays();

                    //将标记物添加到地图上
                    // point 指定标记物应该在哪里
                    let point = new BMap.Point(pt.lng, pt.lat);

                    // 创建标注
                    let marker = new BMap.Marker(point);

                    // 将标注添加到地图中
                    map.addOverlay(marker);

                    //跳动的动画
                    marker.setAnimation(BMAP_ANIMATION_BOUNCE);

                });

            })


        },

        //更新时开启地图
        openMap02(location){

            let _this = this;

            this.mapVisible = true;

            let long = location.split(",")[0];

            let lat = location.split(",")[1];

            let p = new BMap.Point(long, lat);

            let map = new BMap.Map("mapContainer02");

            map.centerAndZoom(p, 15);

            // 创建标注
            let m = new BMap.Marker(p);

            // 将标注添加到地图中
            map.addOverlay(m);

            //跳动的动画
            m.setAnimation(BMAP_ANIMATION_BOUNCE);

            let geoc = new BMap.Geocoder();

            //开启鼠标滚轮缩放
            map.enableScrollWheelZoom(true);

            // 平移缩放控件
            // map.addControl(new BMap.NavigationControl());
            //添加城市列表插件
            let size = new BMap.Size(20, 60);   // size 是在设置地图控件所在的位置
            map.addControl(new BMap.CityListControl({
                anchor: BMAP_ANCHOR_TOP_LEFT,
                offset: size,
                // 切换城市之前事件
                /*onChangeBefore: function(){

                   alert('before');
                },
               // 切换城市之后事件
               onChangeAfter:function(){
                  alert('after');
                }*/
            }));




            //添加地图点击事件
            map.addEventListener("click", function (e) {


                let pt = e.point;
                //将点击的地图经纬度回显到输入框中
                _this.formData.location = pt.lng + "," + pt.lat;

                //对点击的地址进行解析(逆解析)
                geoc.getLocation(pt, function (rs) {

                    let addComp = rs.addressComponents;
                    let address = "";
                    addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber;

                    if(addComp.province){
                        address += addComp.province;
                    }

                    if(addComp.city){
                        address +="," +  addComp.city;
                    }

                    if( addComp.district){
                        address += " , " + addComp.district;
                    }

                    if(addComp.street){
                        address += " , " + addComp.street;
                    }

                    if(addComp.streetNumber){
                        address +=" , " + addComp.streetNumber;
                    }

                    if(_this.chargeAddress(address)){
                        _this.$message.success(address);
                    }else{

                        _this.$message.warning(address + "  当前地址不可用");
                    }


                    _this.formData.address = address;

                    //在地图上添加标记物 （首先需要清空所有的标记物）
                    map.clearOverlays();

                    //将标记物添加到地图上
                    // point 指定标记物应该在哪里
                    let point = new BMap.Point(pt.lng, pt.lat);

                    // 创建标注
                    let marker = new BMap.Marker(point);

                    // 将标注添加到地图中
                    map.addOverlay(marker);

                    //跳动的动画
                    marker.setAnimation(BMAP_ANIMATION_BOUNCE);

                });

            })

        },

        //确定选取的地址
        confirmMap() {


            let _this = this;

            let address = this.formData.address;

            this.$confirm("您确定要选择这个地址信息吗?" , "确定地址" , {

                confirmButtonText:"确定",
                cancelButtonText:"取消",
                type:"warning"

            })
            .then(function(){

                if(_this.chargeAddress(address)){

                    _this.$message.success("体检中心地址选取成功");

                    //为旧地址进行赋值
                    _this.lastLocation = _this.formData.location;
                    _this.lastAddress = _this.formData.address;

                    _this.mapVisible = false;

                }else{

                    _this.$message.warning("您选取的地址不合理,必须要精确到街道,请重新选取地址");

                }



            }).catch(function(){


                _this.$message.info("操作取消");

            })


        },

        //取消选取地址
        cancelMap() {

            let _this = this;

            this.$confirm("您确定要取消这次选择吗?", "取消地址选取", {

                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"

            })
            .then(function () {
                //确认取消



                _this.formData.address = _this.lastAddress;
                _this.formData.location = _this.lastLocation;


                _this.mapVisible = false;

            })
            .catch(function () {
                _this.$message.info("操作取消");
            })

        },

        prepareUpdate(row){

            let _this = this , id = row.id;

            axios.get("/address/prepareUpdate.do?addressId="+id)

                .then(function (resp) {

                    if(resp.data.flag){

                        _this.formData = resp.data.data;

                        _this.updateFormVisible = true;

                        _this.lastLocation = _this.formData.location;
                        _this.lastAddress = _this.formData.address;




                        if(resp.data.data.image){

                            _this.imageUrl = "http://qgivvdn22.hd-bkt.clouddn.com/" + resp.data.data.image;

                            _this.hasOldImg = resp.data.data.image;

                        }


                    }else{

                        _this.$message.warning(resp.data.message);

                    }

                })




        },

        closeUpdateForm() {

            this.resetForm();

            this.updateFormVisible = false;

        },

        updateAddress() {

            //首先进行校验
            let _this = this;

            this.$refs['updateForm'].validate(function(res){

                if(res){
                    //校验通过

                    axios.post("/address/updateAddress.do?hasOldImg="+ _this.hasOldImg , _this.formData)
                        .then(function(resp){

                            if (resp.data.flag) {

                                _this.$message.success(resp.data.message);
                                _this.closeUpdateForm();
                                _this.findWithPage();

                            }else{

                                _this.$message.warning(resp.data.message);

                                _this.closeUpdateForm();

                            }


                        })
                        .catch(function(error){

                            _this.$message.warning(error);

                        })



                }else{

                    _this.$message.warning("您更改的数据不符合校验规则，请检查后重试");



                }

            })
        },

        deleteAddress(row){

            let _this = this , id = row.id;

            this.$confirm("您确定要删除这条地址信息吗?" , "删除地址" , {

                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type:"warning"

            }).then(function(){
                //点击确定按钮

                //发送请求实现删除
                axios.get("/address/deleteAddress.do?addressId="+id)
                    .then(function(resp){

                        if(resp.data.flag){

                            _this.findWithPage();

                            _this.$message.success(resp.data.message);


                        }else{

                            _this.$message.warning(resp.data.message);

                        }


                    })




            }).catch(function(){
                //点击取消按钮

                _this.$message.info("取消删除操作");

            })


        },

        handleCurrentPageChange(currentPage) {

            this.pagination.currentPage = currentPage;
            this.findWithPage();

        },

        handlePageSizeChange(pageSize) {

            this.pagination.pageSize = pageSize;
            this.findWithPage();

        },
    },
    created(){

        this.findWithPage();

        let _this = this;
        axios.get("/common/findAllAuthority.do")
            .then(function(resp){
                _this.authority = getAuthority(_this.authority , resp.data.data);
            })

    }
});